package vip.xiaonuo.util;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class Base64ToImg {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    /**
     * 将base64的文本转换成图片
     * @param text
     * @param path
     * @return
     */
    public static String generateImage(String text, String path) {
        OutputStream out = null;
        // 解密
        try {
            // 生成图片目录
            String dir = path + File.separator + sdf.format(new Date()) + (File.separator);

            File f = new File( dir );
            if(!f.exists()){
                f.mkdirs();
            }

            String imgFileName = UUID.randomUUID().toString().concat(".jpg");

            // 解密
            text = text.substring(text.indexOf(",", 1) + 1, text.length());
            byte[] b = Base64.getDecoder().decode(text);
            // 处理数据
            for (int i = 0; i < b.length; ++i)
                if (b[i] < 0)  b[i] += 1024;

            // 保存图片
            String imgFullPath = dir.concat(imgFileName);
            out = new FileOutputStream(imgFullPath);
            out.write(b);
            // 返回文件全路径
            return imgFullPath;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            if(out!= null ){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *
     * @param text base64格式的字符串
     * @param path 文件保存位置
     * @return
     */
    public static File generateFile(String text, String path){
        return new File(generateImage(text,path));
    }


    public static MultipartFile getMultipartFile(String text, String path) throws IOException {
        File file = generateFile(text,path);
        try{
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), null, new FileInputStream(file));
            return multipartFile;
        }finally {
            file.delete();
        }
    }
}
